package top.gytf.unifiedcall.support.web.mvc.producer;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MissingRequestValueException;
import top.gytf.distools.springboot.ConditionalOnProperty;
import top.gytf.unifiedcall.common.api.ApiDefinitionFactory;
import top.gytf.unifiedcall.model.exception.builtin.InvalidParameterException;
import top.gytf.unifiedcall.producer.response.ResponseHandlerManager;
import top.gytf.unifiedcall.producer.support.exception.CompositeExceptionAdapter;
import top.gytf.unifiedcall.producer.support.exception.ExceptionAdapter;
import top.gytf.unifiedcall.producer.support.exception.SimpleExceptionAdapter;
import top.gytf.unifiedcall.support.producer.response.UnifiedCallProducerResponseProperties;

import java.util.List;

import static top.gytf.unifiedcall.support.producer.response.UnifiedCallProducerResponseProperties.Fields.enable;

/**
 * 统一调用-响应处理 对于 WebMvc的支持的自动配置
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(properties = UnifiedCallProducerResponseProperties.class, name = enable, havingValue = "true", matchIfMissing = true)
public class WebMvcResponseHandlerSupportAutoConfiguration {
    @Bean
    public ExceptionAdapter webMvcExceptionAdapter() {
        return new CompositeExceptionAdapter(List.of(
                new SimpleExceptionAdapter<>(MissingRequestValueException.class, e -> new InvalidParameterException(e.getMessage(), e))
        ), Integer.MAX_VALUE);
    }

    @Bean
    public UnifiedCallResponseHandleAdapter unifiedCallResponseHandleAdapter(ApiDefinitionFactory apiDefinitionFactory,
            ResponseHandlerManager responseHandlerManager, ObjectMapper objectMapper) {
        return new UnifiedCallResponseHandleAdapter(apiDefinitionFactory, responseHandlerManager, objectMapper);
    }
}
